﻿
function fs(){};
fs = {
	viewer : {},
	//viewerid : {},
	owner : {},
	viewer_friends : {},
	owner_friends :{},
	saledata:{},
	friendids:'',
	//self : false,
	people:{},
	init : function(){
	//gadgets.window.adjustHeight(600);
		msg = new gadgets.MiniMessage(0, document.getElementById('message'));
		var tabs = new gadgets.TabSet(0,"首页",document.getElementById('tabs'));
		tabs.addTab("首页",{contentContainer:document.getElementById('fragment-1'),callback:changeSelectedTab});
		tabs.addTab("排行榜",{contentContainer:document.getElementById('fragment-2'),callback:changeSelectedTab});
		tabs.addTab("帮助",{contentContainer:document.getElementById('fragment-3'),callback:changeSelectedTab});
		tabs.alignTabs('left',2);
		fs.loadOwnerData();
		
	},
	showMessage : function(message) {
		var m1 = msg.createStaticMessage(gadgets.json.stringify(message),3);
		gadgets.window.adjustHeight();
	},
	msgBox:function(message,callback){
		var params = {
			title:"消息",
			width:300,
			height:100
		};
		params["message"] = message;
		params["message"] += '<div>' + 
'<p><input type="button" id="exitbutton" value="&nbsp;&nbsp;确定&nbsp;&nbsp;"/></p>' + 
'</div>';
		fs.showDialog(params,callback);
	},
	showDialog : function(options,callback){
		var default_option = {title:"dialog",width:400,height:100};
		var op = $.extend(default_option,options);
		
		var dialoghref = '#TB_inline?height='+op.height+'&width='+op.width+'&inlineId=dialogcontent'+(op.modal?'&modal=true':'');
		var dialog = $('#dialog');
		dialog.attr('href',dialoghref);
		dialog.attr('title',op.title);
		$('#dialogmessage').html(op.message);
		if (callback && typeof(callback) == "function") {
			$('#exitbutton').click(function(){
									//tb_remove(); 
									callback();
									}
			);
		}
		dialog.click();
	},
	loadOwnerData:function(){
		var req = opensocial.newDataRequest();
		req.add(req.newFetchPersonRequest(opensocial.DataRequest.PersonId.VIEWER),'v');
		req.add(req.newFetchPersonRequest(opensocial.DataRequest.PersonId.OWNER),'o');
		req.add(req.newFetchPeopleRequest(opensocial.DataRequest.Group.OWNER_FRIENDS),'of');
		req.send(fs.loadOwnerDataOver);
	},
	loadOwnerDataOver:function(data){
		fs.viewer = data.get('v').getData();
		fs.viewerid = fs.viewer.getId();
		fs.owner = data.get('o').getData();
		fs.ownerid = fs.owner.getId();
		fs.friendids = fs.ownerid;
		fs.self = fs.viewerIsOwner();
		fs.owner_friends = data.get('of').getData();
		
		fs.people[fs.viewerid] = fs.viewer;
		fs.people[fs.ownerid] = fs.owner;
		if(fs.owner_friends)
		fs.owner_friends.each(function(person){
			fs.people[person.getId()] = person;
			fs.friendids += "," + person.getId();
		});
		
		fs.loadSaleData(fs.owner,function(data){
			fs.saledata = gadgets.json.parse(data.text)
			fs.showOwnerData();
			fs.showMessage('load complete');
		});
	},
	loadSaleData:function(person,callback){
		//var url = fs.remoteServer + "/get";
		var data = {};
		//data["id"] = person.getId();
		data["name"] = person.getDisplayName();
		data["thumbnail"] = person.getField(opensocial.Person.Field.THUMBNAIL_URL);
			
		//fs.post(url,data,callback);
			
		var params = "get?" + gadgets.io.encodeValues(data);
		fs.send(params,callback);
	},
	showOwnerData:function(){
		var pdata = fs.saledata[fs.ownerid];
		
		$('#name').text(fs.owner.getDisplayName());
		$('#price').text('¥'+pdata.price);
		$('#cash').text('¥' + pdata.cash);
		if(pdata.status)
		$('#status').text(pdata.status);
		
		if(pdata.master == null || pdata.master == "")
		{
			$('#master').text(fs.getNoun().n + fs.getNoun().v + "自由的.");
		}else{
			$('#master').text("现在的主人是:"+pdata.master.name);
		}
		
		$('#slavenum').text(pdata.slaves.length);
		$('#thumbnail').html('<img src="'+fs.owner.getField(opensocial.Person.Field.THUMBNAIL_URL)+'" width="120px" height="120px">');
		fs.showActionData(pdata.master,'actions');
		fs.showSlaveData(pdata.slaves,'hasslavelist');
		fs.showHistoryData(pdata.history,'hassalelist');
		
		gadgets.window.adjustHeight();
		
	},
	showFriends:function(friends,div){
		var text = "";
		if(friends)
		friends.each(function(person){
			var sdata = fs.saledata[person.getId()];
			var action1 = "<a href='javascript:buy(\""+person.getId()+"\",\"\")'>购买</a>";
			text += "<a href=\"javascript:gofriend("+person.getId()+")\">" + person.getDisplayName() + "</a>" +
			" price"+sdata.price+" "+(fs.self?action1:"")+"<br/>";
		});
		
		$('#'+div).html(text);
	},
	showActionData:function(master,div){
		var text="";
		if(!self)return;
		if(!master || master ==""){
	}else{
		text += "<li><a href=\"javascript:stuffdialog('"+master.id+"','flirt')\">讨好主人</a></li>" +	"<li><a href=\"javascript:stuffdialog('"+master.id+"','2')\">我要赎身</a></li>";

	}
		$('#'+div).html(text);
	},
	showSlaveData:function(slaves,div){
		var u = fs.remoteServer+"/slaves?viewerid="+fs.viewerid+"&ownerid="+fs.ownerid;
		fs.makeNoCachedRequest(u,function(data){
			$('#'+div).html(data.text);
			gadgets.window.adjustHeight();
	},{});
		
	},
	showHistoryData:function(history,div){
		//var text = "";
		//for(var i =0;i < history.length;i++){
		//	text += history[i].text + " "+ history[i].time + "<br/>";
		//}
		var u = fs.remoteServer + "/history?viewerid="+fs.viewerid+"&ownerid="+fs.ownerid;
		fs.makeNoCachedRequest(u,function(data){
			$('#'+div).html(data.text);
			gadgets.window.adjustHeight();
	},{});
		
	},
	viewerIsOwner : function() {
            return (fs.viewer.getId && fs.viewer.getId() || -1) ===
                   (fs.owner.getId && fs.owner.getId() || -2);
    },
	getNoun:function(){
		if(fs.viewerIsOwner()){
			return {n:"你",v:"是"};
		}else{
			if(!fs.owner.getField(opensocial.Person.Field.GENDER))return "TA";
			if(fs.owner.getField(opensocial.Person.Field.GENDER).key == "MALE"){
				return {n:"他",v:"是"};
			}else
				return {n:"她",v:"是"};
		}
	},
	remoteServer:"http://app.myopen.com/fs/Sale",
	remoteHtml:"http://app.myopen.com/fs",
	send:function(params,callback){
		//sender id
		params += ["&viewerid=",fs.viewerid,"&ownerid=",fs.ownerid].join("");
		var url = fs.remoteServer + "/" + params ;//+ "&id="+ fs.viewer.getId();
		fs.makeNoCachedRequest(url, callback, null);
	},
//	updatePerson:function(url,person,callback){
//			var data = {};
//			data["id"] = person.getId();
//			data["name"] = person.getDisplayName();
//			data["thumbnail"] = person.getField(opensocial.Person.Field.THUMBNAIL_URL);
			
//			fs.post(url,data,callback);
			
//	},
	post:function(url,data,callback){
		var params = {};
		params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
		params[gadgets.io.RequestParameters.POST_DATA] = gadgets.io.encodeValues(data);
		gadgets.io.makeRequest(url, callback, params);
	},
	makeCachedRequest:function(url, callback, params, refreshInterval) {
		var ts = new Date().getTime();
		var sep = "?";
		if (refreshInterval && refreshInterval > 0) {
			ts = Math.floor(ts / (refreshInterval * 1000));
		}
		if (url.indexOf("?") > -1) {
			sep = "&";
		}
		url = [ url, sep, "nocache=", ts ].join("");
		gadgets.io.makeRequest(url, callback, params);
	},
	makeNoCachedRequest:function(url, callback, params) {
		var ts = new Date().getTime();
		var sep = "?";
		ts = Math.floor(ts / 1000);
		if (url.indexOf("?") > -1) {
			sep = "&";
		}
		url = [ url, sep, "nocache=", ts ].join("");
		gadgets.io.makeRequest(url, callback, params);
	}
};
function buy(slave,nickname){
		var params = "buy?slaveid="+slave+"&nick="+nickname;
		fs.send(params,function(data){
			//messagebox result
			fs.msgBox(data.text,function(){
			tb_remove();
			postActivity(data.text,null);
			window.location.reload();
			
			});
		});

	}
function dostuff(slave,actionid){
		var params = "dostuff?slaveid="+slave+"&stuffid="+actionid;
		fs.send(params,function(data){
			fs.msgBox(data.text,function(){
				tb_remove();
				fs.showHistoryData(null,'hassalelist');
				fs.showSlaveData(null,'hasslavelist');
				
				postActivity(data.text,null);
			});
		});
		
	}
	
function getRadioValue(radio){
	var v = $('input[@name='+radio+'][@checked]').val();
	if(!v){
		if(document.getElementById(radio))
		v = document.getElementById(radio).value;
	}
 return v;
}

function postActivity(title,body){
	var params = {};
	params[opensocial.Activity.Field.TITLE] = title;
	params[opensocial.Activity.Field.BODY] = body;
	try{
	var activity = opensocial.newActivity(params);
	opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.HIGH);
	}catch(e){
	}
}